package com.personal.task;

import com.personal.po.ResourcesViewPO;
import com.personal.service.ResourcesService;
import com.personal.utils.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Component
@Slf4j
public class ResourcesViewTask {

    @Resource
    private RedisUtils redisUtils;

    @Autowired
    private ResourcesService resourcesService;

    @Scheduled(cron = "0 0 1 * * ?")
//    @Scheduled(cron = "0 0/2 * * * ?")
    @Transactional(propagation = Propagation.SUPPORTS, rollbackFor = Exception.class)
    public void createHyperLog(){
        log.info("浏览量入库开始");
        //先拿到所有的文章id
        List<Long> list = resourcesService.getAllResourcesId();
        list.forEach(resourcesId -> {
            //获取每一篇文章的浏览量存入到数据库中
            String key = "resourcesId_" + resourcesId;
            Long view = redisUtils.size(key);
            if (view > 0){
                ResourcesViewPO resourcesViewPo = resourcesService.getById(resourcesId);
                Long views = resourcesViewPo.getViewCount() + view;
                //新浏览量
                resourcesViewPo.setViewCount(views);
                int num = resourcesService.updateResourcesView(resourcesViewPo);
                if (num != 0){
                    log.info("数据库更新后的浏览量为：{}", views);
                    redisUtils.del(key);
                }
            }
        });
        log.info("浏览量更新完毕");
    }

}
